package com.atguigu.chapter11.window;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.*;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.expressions.Expression;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.lit;

/**
 * Author: Pepsi
 * Date: 2023/8/24
 * Desc:
 */
public class Flink01_Window_Group_1 {
    public static void main(String[] args) {

        // 获取流执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStream<WaterSensor> stream = env.fromElements(
                new WaterSensor("sensor_1", 1000L, 10),
                new WaterSensor("sensor_1", 2000L, 20),
                new WaterSensor("sensor_2", 3000L, 30),
                new WaterSensor("sensor_1", 4000L, 40),
                new WaterSensor("sensor_1", 5000L, 50),
                new WaterSensor("sensor_1", 6000L, 60)
        )
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((ws,ts)->ws.getTs())
                );

        // 获取表执行环境，在这之前要获取流的执行环境作为参数传过来
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);

        // 把流转换成表
        Table table = tEnv.fromDataStream(stream, $("id"), $("ts"), $("vc"), $("et").rowtime());

        // 定义窗口，用tableapi的方式来实现窗口 literal 字面量 1 3 "abc"   ；  参数定义窗口的长度，5秒的窗口，作用在哪个字段上面，最后起别名
//        GroupWindow win = Tumble.over(Expressions.lit(5).second()).on($("et")).as("w");
        // 滑动窗口  滑动窗口大小5s,滑动步长2s
//        GroupWindow win = Slide.over(lit(5).second()).every(lit(2).second()).on($("et")).as("w");
        // 会话窗口，设置gap
        GroupWindow win = Session.withGap(lit(2).second()).on($("et")).as("w");



        table
                // 因为这里要传一个groupwindow,所以要在上面定义
                .window(win)
                // 根据id和窗口分组
                .groupBy($("id"),$("w")) // 如果分组的时候没有id，那就相当于是windowAll
                .select($("id"),$("w").start(),$("w").end(),$("vc").sum().as("sum_vc"))
                .execute()
                .print();


    }
}
